package com.mrzhou.core.tool.api;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * 统一的JSON返回格式
 * @param <T>
 */
@Getter
@Setter
public class R<T> implements Serializable {

    private static final Long serialVersionUID = 1L;

    @ApiModelProperty(value = "状态码", required = true)
    private int code;

    @ApiModelProperty(value = "是否成功", required = true)
    private boolean success;

    @ApiModelProperty("承载的数据")
    private T data;

    @ApiModelProperty(value = "返回的消息", required = true)
    private String msg;

    public R() { }

    private R(IResultCode resultCode) {
        this(resultCode, null, resultCode.getMessage());
    }

    private R(IResultCode resultCode, String msg) {
        this(resultCode, null, msg);
    }

    private R(IResultCode resultCode, T data) {
        this(resultCode, data, resultCode.getMessage());
    }

    private R(IResultCode resultCode, T data, String msg) {
        this(resultCode.getCode(), data, msg);
    }

    private R(int code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
        this.success = ResultCode.SUCCESS.getCode() == code;
    }

    /**
     * 请求成功响应, 不携带响应数据
     */
    public static <T> R<T> success(IResultCode result, String msg) {
        return new R(result, msg);
    }

    public static <T> R<T> success(String msg) {
        return new R(ResultCode.SUCCESS, msg);
    }

    /**
     * 携带响应数据
     */
    public static <T> R<T> data(T data) {
        return new R(ResultCode.SUCCESS, data);
    }

    public static <T> R<T> data(T data, String msg) {
        return new R(ResultCode.SUCCESS, data, msg);
    }

    public static <T> R<T> data(int code, T data, String msg) {
        return new R(code, data, null == data? "暂无承载数据": msg);
    }

    /**
     * 错误消息返回
     */
    public static <T> R<T> fail(int code, String msg) {
        return new R(code, (Object)null, msg);
    }

    public static <T> R<T> fail(String msg) {
        return new R(ResultCode.FAILURE, msg);
    }

    public static <T> R<T> fail(IResultCode code, String msg) {
        return new R(code, msg);
    }

    public static <T> R<T> status(boolean status) {
        return status ? success("操作成功！") : fail("操作失败！");
    }

}
